package com.sam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Logger;

import javax.mail.Session;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.google.api.client.json.JsonToken;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.appengine.labs.repackaged.org.json.JSONTokener;
import com.opensymphony.xwork2.ActionSupport;

public class GmailService extends ActionSupport implements ServletResponseAware, ServletRequestAware {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 4394230103125334180L;
	
	private static final Logger log = Logger.getLogger(GmailService.class.getName());


	
	public String execute1(){
		
		String longUrl = "https://developers.google.com/accounts/docs/OAuth2WebServer";
		
		try {
	        ArrayList scopes = new ArrayList();
	        scopes.add("https://www.googleapis.com/auth/urlshortener");
	        AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
	        AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
	        // The token asserts the identity reported by appIdentity.getServiceAccountName()
	        JSONObject request = new JSONObject();
	        request.put("longUrl", longUrl);

	        URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setRequestMethod("POST");
	        connection.addRequestProperty("Content-Type", "application/json");
	        connection.addRequestProperty("Authorization", "OAuth " + accessToken.getAccessToken());
	        
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	        request.write(writer);
	        writer.close();
	        log.warning(String.valueOf(connection.getResponseCode()) );
	        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        	log.warning("paso!!!!" + String.valueOf(connection.getResponseCode()) );
	            // Note: Should check the content-encoding.
	            //JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
	            //JSONObject response = new JSONObject(response_tokens);
	            //return (String) response.get("id");
	        } else {
	            throw new Exception();
	        }
	    } catch (Exception e) {
	        // Error handling elided.
	        
	    }
		return SUCCESS;
	}
	
	
	public String execute2() {
		for(Cookie c : servletRequest.getCookies()) {
			log.warning(c.getName());
			log.warning(c.getValue());
		    
		  }
		
		UserService userService = UserServiceFactory.getUserService();
		ArrayList scopes = new ArrayList();
        scopes.add("https://mail.google.com/");
        AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
        AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
        
       // accessToken.
		
		
		try {
			log.warning(accessToken.getAccessToken());
			URL url = new URL("https://mail.google.com/mail/feed/atom/");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			//connection.setRequestProperty("Cookie", "WML=1340039172561#martinrico@mycrazymula.com.ar:267:0; S=gmail=Olx9t-o3bk73UT4_0u8lug; GX=DQAAAP4AAACuEDKlCOAXw3Ib0OZI9RqG3oExoCSxUU02MLZ-KlKlHldDZ8bjG9MR7Dkonpa23MU8-Lyz42sr4gGJ57pMuYkMABoSKME2HQ_FhG_kbFRG0E76o5A21vjHR9fbkF9EIYXwOfGhVYgxPhV0ZiD52-yxFIAGldZlNVfaqmoRcKzRFJOYTcOcySqLjmSOhAmjJtgxkFRWc1znQmeYFPW4R2DEkwYbWvpm2CkE279KbDYReKqeBK4le_8tpSzIBFk4LufGN0F8rLqc9pko9v5h1I3u68DQyA5bGVZ_Ie6NtkjUPlC4OmkrENLcWVGQP_AeotE2iB3ErcQA3Qt49ISY1YNp; PREF=ID=c49677ba07dd4a52:U=8b9fdee8b35097fc:FF=0:LD=en:CR=2:TM=1338214805:LM=1339080380:GM=1:S=cl09ZWAJG-khTYeA; NID=61=e_Vaj6585BIbOFWUZjojIIFu3eXrWpCSogJ0NSzpufe8cJRf8abwi0h2eQGGZt1hI7YIelLkGss99nf8VDteRl1a4PgpZ6Uuyerw0xYRxtwh0mxSv08FbhRsTFbH1_3Clm9ojW0ay_U57_NCgV9OAXwlEbUTZRwccUOWUne54Fvg7NMxksayb2qRnAkzIg; SID=DQAAAPwAAAAPLRxnhu1b8fP3k1ebbHh_1Ue4BBDaGxYfddyK4jyvHV45IUuF3mXXhxWX9MqyBRJ3l7D1W5uyCIgDJQ5-i_r86rA2K4l_gtobZvPsOs4dZrlZV_SAvX7Km8WBHwRk6fTxs4d1uNGejHFmq04lltISrBw-WL45wRBDj2QSr9LTDyL39VFNs1PCPBo4ZBYzPxuDVjyUTVcjKM_MNlBiUVZppvGtN9F86K044ngwWT1XBUDtOQe8LPqtAjJrBJ5sj4IX5EkxGO5dbLIHwz-eOMd4Sua1AHXXVvUQsRPxMLmZjyLcFy91D2tpjyp3s9H-wiaIx4snMrNbB9ed82f-t8oB; HSID=AsFOw9RuqebumWyJn; SSID=Atfc0pXvW7wx5OWEJ; APISID=7rKoxqZH5RXkVUl6/AuB1w1_KyQJ2UBSbO; SAPISID=22Vmw8jbVmIgTJFq/A-c1Bkaa4XdqSdHbT");
			//connection.setRequestProperty("Cookie", "WML=1340039172561#martinrico@mycrazymula.com.ar:267:0; S=gmail=Olx9t-o3bk73UT4_0u8lug; GX=DQAAAP4AAACuEDKlCOAXw3Ib0OZI9RqG3oExoCSxUU02MLZ-KlKlHldDZ8bjG9MR7Dkonpa23MU8-Lyz42sr4gGJ57pMuYkMABoSKME2HQ_FhG_kbFRG0E76o5A21vjHR9fbkF9EIYXwOfGhVYgxPhV0ZiD52-yxFIAGldZlNVfaqmoRcKzRFJOYTcOcySqLjmSOhAmjJtgxkFRWc1znQmeYFPW4R2DEkwYbWvpm2CkE279KbDYReKqeBK4le_8tpSzIBFk4LufGN0F8rLqc9pko9v5h1I3u68DQyA5bGVZ_Ie6NtkjUPlC4OmkrENLcWVGQP_AeotE2iB3ErcQA3Qt49ISY1YNp; PREF=ID=c49677ba07dd4a52:U=8b9fdee8b35097fc:FF=0:LD=en:CR=2:TM=1338214805:LM=1339080380:GM=1:S=cl09ZWAJG-khTYeA; NID=61=e_Vaj6585BIbOFWUZjojIIFu3eXrWpCSogJ0NSzpufe8cJRf8abwi0h2eQGGZt1hI7YIelLkGss99nf8VDteRl1a4PgpZ6Uuyerw0xYRxtwh0mxSv08FbhRsTFbH1_3Clm9ojW0ay_U57_NCgV9OAXwlEbUTZRwccUOWUne54Fvg7NMxksayb2qRnAkzIg; SID=DQAAAPwAAAAPLRxnhu1b8fP3k1ebbHh_1Ue4BBDaGxYfddyK4jyvHV45IUuF3mXXhxWX9MqyBRJ3l7D1W5uyCIgDJQ5-i_r86rA2K4l_gtobZvPsOs4dZrlZV_SAvX7Km8WBHwRk6fTxs4d1uNGejHFmq04lltISrBw-WL45wRBDj2QSr9LTDyL39VFNs1PCPBo4ZBYzPxuDVjyUTVcjKM_MNlBiUVZppvGtN9F86K044ngwWT1XBUDtOQe8LPqtAjJrBJ5sj4IX5EkxGO5dbLIHwz-eOMd4Sua1AHXXVvUQsRPxMLmZjyLcFy91D2tpjyp3s9H-wiaIx4snMrNbB9ed82f-t8oB; HSID=AsFOw9RuqebumWyJn; SSID=Atfc0pXvW7wx5OWEJ; APISID=7rKoxqZH5RXkVUl6/AuB1w1_KyQJ2UBSbO; SAPISID=22Vmw8jbVmIgTJFq/A-c1Bkaa4XdqSdHbT");
			connection.addRequestProperty("Authorization", "OAuth " + accessToken.getAccessToken());
			//connection.setRequestProperty("Cookie", "AJKiYcFDHptv9kyHE_AjgizUHnkmgqQaNeqrZyxNrklskQow-k3_7cPANAwa1MumbRT_bc4DU3vw9yrKIM2vqHxXZbzagzTXbEfJwk4Do0yZTCmKO7iVpdSV7-3rjPOjHmMylcK6G8y0OFI5FKqVuA0Fft41lZyqoMhG3tRujfctuY0Wb3-AYTB49nPj6Np7T_w2nYkNCf9sFnORH4vufPkgNWE1HuUXyqZPy7GIW_roYH6AZZeI9Avsl5aN90b3oCJ76bvINr2UMayja_zSu5CYH23g73c3Z0Vt48GRxdvFU494FNsYTyzxqQS1V87gTowyVPHBerybRZkFBFfObeBQAzLP8FzGaDzhEGqWt7us_pB49mGUtDAApJi4F3b5IJuGC_EByjqVvqDuqgFVorq_eyDyu-d4t82a4rjlFlm8VEizRXiCyFSKxaA_t7be72WvuJA2Y29mUyhv0kqs-YHLwHkSjfaUJp7H0AEjm8g7FWMCOU5XQ3HEPEt2GpK5aEMDWnokJ9srV0JdogwQV2zcQlZ9RzSC9Ktx5t0EHiNVBtgL0bu9A64HUPDNbv3tdpEOh4M-1Gz361pn8b8DhOk6ud8E6p6rwJ3L-WlI49J901orOSx64gPv_JHZCafThA_zlxfsy7jfANgtsRGlFDX8bCwHaGiENSe22vSgOaxUkGdOoDkB5iN6paKtd6-773kKNv61VW67");
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			
			while ((line = reader.readLine()) != null) {
				log.warning(line);
			}
			reader.close();
			
		} catch (MalformedURLException e) {
			// ...
		} catch (IOException e) {
			// ...
		}
		
		return SUCCESS;
	}
	
	
	
	public String execute() {
		//Session.getDefaultInstance(properties)
		
		return SUCCESS;
	}
	
	
	
	
	

	protected HttpServletResponse servletResponse;
	  @Override
	  public void setServletResponse(HttpServletResponse servletResponse) {
	    this.servletResponse = servletResponse;
	  }

	  protected HttpServletRequest servletRequest;
	  @Override
	  public void setServletRequest(HttpServletRequest servletRequest) {
	    this.servletRequest = servletRequest;
	  }
	

}
